﻿using System;
using System.Linq;
using DotNetNuke.Entities.Users;
using DotNetNuke.UI.ControlPanels;

namespace BrandonHaynes.Providers.ControlPanel
    {
    /// <summary>
    /// A top-level control panel that is registered with DotNetNuke and
    /// identifies on a per-request basis the "best" control panel to display
    /// for a given user.
    /// 
    /// For administrators, hosts, page-admins, and module-admins, this control
    /// will defer to the control panel defined under the "administrators" key.
    /// If no control panel mapping is identified, the "null" control panel will
    /// be used.
    /// </summary>
    public class Demultiplex : NestedControlPanelBase
        {
        /// <summary>
        /// The key associated with the control panel used for
        /// administrators, hosts, page-admins, and module-admins
        /// </summary>
        public const string AdministratorControlPanel = "administrators";
        /// <summary>
        /// The key associated with the default control panel, which is 
        /// used when no other mapping is authorized.
        /// </summary>
        public const string DefaultControlPanel = "null";

        protected override void OnInit(EventArgs e)
            {
            base.OnInit(e);
            Controls.Add(ControlPanel);
            }

        /// <summary>
        /// Get an instance of the best-fit control panel for this request
        /// </summary>
        private ControlPanelBase ControlPanel
            { get { return ControlPanelProvider.GetControlPanel(MappingName); } }

        /// <summary>
        /// Identify the name of the mapping best associated with this request.
        /// If an administrator, host, page-admin, or module-admin, the "administrator"
        /// key is returned.  If no mapping is identified, "null".
        /// </summary>
        private string MappingName
            {
            get
                {
                return IsPageAdmin() || IsModuleAdmin()
                        ? AdministratorControlPanel
                        : ControlPanelProvider.GetAuthorizedControlPanels(UserController.GetCurrentUserInfo())
                            .Select(mapping => mapping.Name)
                            .FirstOrDefault() ?? DefaultControlPanel;
                }
            }

        /// <summary>
        /// Gets the mapping currently associated with this request
        /// </summary>
        public ControlPanelMapping CurrentMapping
            { get { return ControlPanelProvider.Mappings[MappingName]; } }
        }
    }